﻿using MesGLApp.BLL.Mes;
using MesGLApp.DAL.MesDB;
using Smobiler.Core;
using Smobiler.Core.Controls;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Text;
using System.IO;
using System.Linq;
using System.Text;

namespace MesGLApp.View.Scan
{
    partial class ExcepOrderCreateFrm : Smobiler.Core.Controls.MobileForm
    {
        #region "内部变量"
        private ExcepOrderControler _ctrl = new ExcepOrderControler();

        private List<SiteInfo> _site_list = new List<SiteInfo>();
        private List<StatusInfo> _status_list = new List<StatusInfo>();

        private SiteInfo _curr_site = null;
        private StatusInfo _curr_status = null;
        #endregion

        public ExcepOrderCreateFrm() : base()
        {
            //This call is required by the SmobilerForm.
            InitializeComponent();
        }

        #region "控件事件"
        /// <summary>
        /// 关闭本页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClose_Press(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 读入页面时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExcepOrderCreateFrm_Load(object sender, EventArgs e)
        {
            this.InitSiteList();
            this.InitErrStatusList();
        }

        /// <summary>
        /// 打开站点选择列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSite_Press(object sender, EventArgs e)
        {
            if (this._site_list != null && this._site_list.Count > 0)
            {
                this.popSite.ShowDialog();
            }
            else
            {
                MessageBox.Show("您的权限不能操作任何站点！", "提示");
            }
        }

        /// <summary>
        /// 选择站点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void popSite_Selected(object sender, EventArgs e)
        {
            this.btnSite.Text = this.popSite.Selection.Text;
            if (this._site_list != null && this._site_list.Count > 0)
            {
                var query = this._site_list.Where(s => s.SiteName == this.popSite.Selection.Text);
                if (query != null && query.Count() > 0)
                {
                    this._curr_site = query.First<SiteInfo>();
                }
            }
        }

        /// <summary>
        /// 打开异常状态选择列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStatus_Press(object sender, EventArgs e)
        {
            if (this._status_list != null && this._status_list.Count > 0)
            {
                this.popStatus.ShowDialog();
            }
            else
            {
                MessageBox.Show("没有任何异常状态信息！", "提示");
            }
        }


        /// <summary>
        /// 选择异常状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void popStatus_Selected(object sender, EventArgs e)
        {
            this.btnStatus.Text = this.popStatus.Selection.Text;
            if (this._status_list != null && this._status_list.Count > 0)
            {
                var query = this._status_list.Where(s => s.StatusValue == this.popStatus.Selection.Text);
                if (query != null && query.Count() > 0)
                {
                    this._curr_status = query.First<StatusInfo>();
                }
            }
        }

        /// <summary>
        /// 工单扫码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnScan_BarcodeScanned(object sender, BarcodeResultArgs e)
        {
            if (e.Value != null && e.Value.Trim().Length > 0)
            {
                this.txtProdNumber.Text = e.Value.Trim();
            }
        }

        /// <summary>
        /// 获取用户拍照
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cameraButton1_ImageCaptured(object sender, BinaryResultArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(e.error))
                {
                    image1.ResourceMode = ResourceMode.Data;
                    image1.ResourceData = e.Data;
                }
            }
            catch (Exception ex)
            {
                Toast(ex.Message);
            }
        }

        /// <summary>
        /// 获取用户拍照
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cameraButton2_ImageCaptured(object sender, BinaryResultArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(e.error))
                {
                    image2.ResourceMode = ResourceMode.Data;
                    image2.ResourceData = e.Data;
                }
            }
            catch (Exception ex)
            {
                Toast(ex.Message);
            }
        }
        #endregion

        #region "内部方法"
        /// <summary>
        /// 初始化可操作的站点
        /// </summary>
        private void InitSiteList()
        {
            //根据用户查询该用户可以操作的站点
            this._site_list = this._ctrl.SearchSiteInfoForUserID(LoginFrm.LoginUser.id);
            if (this._site_list != null && this._site_list.Count > 0)
            {
                PopListGroup tmpGroup = new PopListGroup();
                foreach (var item in this._site_list.OrderBy(s => s.SiteCode))
                {
                    tmpGroup.AddListItem(item.SiteName, item.ID.ToString());
                }
                this.popSite.Groups.Add(tmpGroup);
            }
        }

        /// <summary>
        /// 初始化异常状态
        /// </summary>
        private void InitErrStatusList()
        {
            //查询所有状态信息
            List<StatusInfo> tmpList = this._ctrl.SearchAllStatus();
            if (tmpList != null && tmpList.Count > 0)
            {
                //只筛选异常状态信息
                var query = tmpList.Where(s => s.StypeID == 4 && s.StatusValue != "暂停" && s.StatusValue != "取消暂停" && s.StatusValue != "无异常").OrderBy(s => s.StatusCode);
                if (query != null && query.Count() > 0)
                {
                    this._status_list.AddRange(query);
                }
            }

            //将异常状态信息绑定到下拉列表中
            if (this._status_list != null && this._status_list.Count > 0)
            {
                PopListGroup tmpGroup = new PopListGroup();
                foreach (var item in this._status_list)
                {
                    tmpGroup.AddListItem(item.StatusValue, item.ID.ToString());
                }
                this.popStatus.Groups.Add(tmpGroup);
            }
        }


        /// <summary>
        /// 检查资料是否正确
        /// </summary>
        /// <param name="tarBean"></param>
        /// <param name="siteBean"></param>
        /// <param name="statusBean"></param>
        /// <returns></returns>
        private string ChechData(TargetProdProcess tarBean, SiteInfo siteBean, StatusInfo statusBean)
        {
            string errString = "";
            decimal tmpDec = 0;
            if (tarBean == null || tarBean.ID <= 0)
            {
                errString = "工单号：" + this.txtProdNumber.Text.Trim() + "\r\n" + "系统中不存在此工单，中止保存！";
            }
            if (tarBean.ErrStatusID == 14)
            {
                errString = "工单当前为暂停状态，不能产生维修单！";
            }
            else if (siteBean == null || siteBean.ID <= 0)
            {
                errString = "当前站点不能为空，中止保存！";
            }
            else if (siteBean.ID != tarBean.CurrSiteID)
            {
                errString = "当前站点与工单所在站点不符，中止保存！";
            }
            else if (statusBean == null || statusBean.ID <= 0)
            {
                errString = "当前异常状态不能为空，中止保存！";
            }
            else if (decimal.TryParse(this.txtErrQty.Text.Trim(), out tmpDec) == false)
            {
                errString = "异常数量必需为数值型数据！";
            }
            else if (decimal.Parse(this.txtErrQty.Text.Trim()) <= 0)
            {
                errString = "异常数量不得小于或等于0！";
            }
            else if (decimal.Parse(this.txtErrQty.Text.Trim()) > tarBean.ProdQty)
            {
                errString = "异常数量不得超过投产数量！";
            }
            return errString;
        }


        /// <summary>
        /// 从界面中收集信息，生成维修单信息
        /// </summary>
        /// <returns></returns>
        private ExcepOrder GetExcepOrder()
        {
            decimal tmpDec = 0;
            ExcepOrder orderBean = new ExcepOrder
            {
                ProdNumber = this.txtProdNumber.Text.Trim(),
                SiteID = this._curr_site.ID,
                SiteName = this._curr_site.SiteName,
                ErrStatusID = this._curr_status.ID,
                ErrStatusName = this._curr_status.StatusValue,
                ErrQty = decimal.TryParse(this.txtErrQty.Text, out tmpDec) ? decimal.Parse(this.txtErrQty.Text) : 0,
                DispStatus = 0,
                Remark = this.txtRemark.Text.Trim()
            };
            return orderBean;
        }

        /// <summary>
        /// 从界面收集图片信息，生成维修单的图片
        /// </summary>
        /// <returns></returns>
        private ExcepPicture GetExcepPicture()
        {
            ExcepPicture picBean = new ExcepPicture()
            {
                ProdNumber = this.txtProdNumber.Text.Trim(),
                Pic01 = this.image1.ResourceData != null ? this.image1.ResourceData : null,
                Pic02 = this.image2.ResourceData != null ? this.image1.ResourceData : null,
            };
            return picBean;
        }
        #endregion




        private void btnSave_Press(object sender, EventArgs e)
        {
            TargetProdProcess targetBean = this._ctrl.SearchTargetProdProcessForProdNo(this.txtProdNumber.Text.Trim());

            string errString = this.ChechData(targetBean, this._curr_site, this._curr_status);
            if (errString != null && errString.Trim().Length > 0)
            {
                MessageBox.Show(errString, "提示");
            }
            else
            {
                ExcepOrder orderBean = this.GetExcepOrder();
                ExcepPicture picBean = this.GetExcepPicture();
                string repNo = this._ctrl.GetMaxRepairNumber();
                if (repNo != null && repNo.Trim().Length > 0)
                {
                    orderBean.RepairNumber = repNo;
                    picBean.RepairNumber = repNo;

                    try
                    {
                        int count = this._ctrl.InsertExcepOrder(orderBean, picBean);
                        if (count > 0)
                        {
                            MessageBox.Show("异常订单下单成功。" + "\r\n" + "点击【是】查看订单信息！", "提示", MessageBoxButtons.YesNoCancel, (object sender1,MessageBoxHandlerArgs args) => {
                                if (args.Result == ShowResult.Yes)
                                {
                                    
                                }
                            });
                            this.ClearData();
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("异常订单下单失败！" + "\r\n" + ex.Message, "提示");
                    }
                }
                else
                {
                    MessageBox.Show("无法生成异常订单号，中止保存！","提示");
                }
            }
        }

        private void ClearData()
        {
            this.btnSite.Text = "请选择站点  >";
            this.btnStatus.Text = "请选择异常  >";
            this.txtProdNumber.Text = "";
            this.txtErrQty.Text = "0";
            this.image1.ResourceData = null;
            this.image2.ResourceData = null;

            this._curr_site = null;
            this._curr_status = null;
        }
    }
}